
package com.jl.util;

import java.math.BigInteger;

/**
 * @version 2012.10.27
 * @author LuHongjun
 */
public class BinUtil {

	/**
	 * delete the number that is not the 1 or 0
	 * 
	 * @param bianry
	 * @return
	 */
	public static String compact(String bianry) {
		StringBuilder sb = new StringBuilder();
		for (char ch : bianry.toCharArray()) {
			if (isBinary(ch)) {
				sb.append(ch);
			}
		}
		return sb.toString();
	}

	/**
	 * foramtted the bianry string to 00000001 00000001 format
	 * 
	 * @param bianry
	 * @return
	 */
	public static String format8X(String bianry) {

		String temp = bianry.replaceAll("\\s+", "");
		// int add = temp.length() % 8;
		// if (add != 0) {
		// for (int i = 0; i < 8 - add; i++) {
		// temp = "0" + temp;
		// }
		// }
		StringBuilder sb = new StringBuilder();
		int count = 0;
		for (char ch : temp.toCharArray()) {
			if (isBinary(ch)) {
				sb.append(ch);
				count++;
			}
			if (count % 8 == 0 && count != 0) {
				sb.append(' ');
			}
		}
		return sb.toString();
	}

	public static boolean isBinary(char ch) {
		if (ch == '0' || ch == '1') {
			return true;
		}
		return false;
	}

	/**
	 * transform the bianry string to hex string(formated)
	 * 
	 * @param binary
	 * @return
	 */
	public static String toHex(String binary) {
		String temp = compact(binary);
		BigInteger bi = new BigInteger(temp, 2);
		String res = bi.toString(16);
		return HexUtil.format(res);
	}

	/**
	 * transform the bianry string to decimal string
	 * 
	 * @param binary
	 * @return
	 */
	public static String toDecimal(String binary) {
		BigInteger bi = new BigInteger(binary, 2);
		return bi.toString(10);
	}
}
